# -*- coding: utf-8 -*-
#控制命令相关的服务器
import threading

__author__ = 'hftec'

from Queue import Queue
import socket
import tcp_thread
import multiprocessing
import simplejson
from lcopa import lcopa_usb
from common import file
import atp_process
resp_json={
    "respCode":200,
    "msg":"ok",
    "data":{"u-phi":[],"lcopas":[]}
}

class TcpServer:
    def __init__(self,img_queue):
        self.address = ('', 8089)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # s = socket.socket()
        self.s.bind(self.address)
        self.s.listen(5)
        self.is_stop = False
        self.server_run = True
        self.cmd_queue = Queue()
        self.img_queue = img_queue
        threading.Thread(target=self.__wait_data).start()
        threading.Thread(target=self.__wait_cmd).start()
        self.atp = atp_process.ATPPorcess(self.img_queue)
        # self.process = multiprocessing.Process(target=self.wait_data)
        self.clients = []
    def __wait_data(self):
        print "tcp server start\r\n"
        try:
            while(self.server_run):
                client, addr = self.s.accept()
                print 'got connected from',addr
                #ss.send('byebye')
                self.clients.append(tcp_thread.TcpThread(client,self.cmd_queue))
        except KeyboardInterrupt:
            self.close()
    def __wait_cmd(self):
        while (self.server_run):
            que = self.cmd_queue.get()
            if(que["cmd"]['opType'] == 1):
                file_list = ([(name.split('/')[-1]) for name in file.GetFileList('./u-phi')])
                resp_json["data"]["u-phi"] =file_list
                lcopausb = lcopa_usb.LcopaUsb()
                usb_ids= lcopausb.get_usb_list()
                resp_json["data"]["lcopas"] = usb_ids
                que["client"].send(simplejson.dumps(resp_json))
            elif(que["cmd"]['opType'] == 2):#开启atp
                resp_json["respCode"]=self.atp.start()
                que["client"].send(simplejson.dumps(resp_json))
            elif(que["cmd"]['opType'] == 3):#关闭atp

                resp_json["respCode"] = self.atp.stop()
                que["client"].send(simplejson.dumps(resp_json))
            elif(que["cmd"]['opType'] == 4):#配置设备
                resp_json["respCode"] = self.atp.setting(que["cmd"])
                que["client"].send(simplejson.dumps(resp_json))
    # def stop_tcp_server(self):
    #     # self.is_stop = True
    #     self.close()
    def close(self):
        self.server_run = False
        # self.process.terminate()
        for c in self.clients:
            c.stop()
        self.s.close()